﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LeetCodeSolutions
{
    /// <summary>
    /// 13.罗马数字转整数
    /// </summary>
    class LeetCode13: LeetCodeBase
    {
        public override void Execute()
        {
            CommonFuntions.Print(RomanToInt("LVIII"));
        }

        public int RomanToInt(string s)
        {
            if (s.Length == 1)
            {
                return GetSymbolValue(s);
            }

            return CaluRomanValue(s);
        }

        public Dictionary<string, int> romanNumTable = new Dictionary<string, int>()
        {
            { "I" , 1 },
            { "V" , 5 },
            { "X" , 10 },
            { "L" , 50 },
            { "C" , 100 },
            { "D" , 500 },
            { "M" , 1000 },
        };

        public List<string> romanSymbolList = new List<string>()
        {
            "I","V","X","L","C","D","M",
        };

        /// <summary>
        /// 间隔是否在2以内
        /// </summary>
        public bool IsNear(string symbol1, string symbol2)
        {
            int index1 = romanSymbolList.IndexOf(symbol1);
            int index2 = romanSymbolList.IndexOf(symbol2);

            return !(Math.Abs(index1 - index2) > 2);
        }

        private int CaluRomanValue(string numStr)
        {
            int length = numStr.Length;
            int value = 0;
            List<int> strValueList = new List<int>();
            for (int i = 0; i < length; i++)
            {
                strValueList.Add(GetSymbolValue(numStr[i].ToString()));
            }

            List<int> tempValueList = strValueList;
            for (int i = 0; i < length - 1; i++)
            {
                if (strValueList[i] < strValueList[i + 1])
                {
                    tempValueList[i] = -tempValueList[i];
                }
                value += tempValueList[i];
            }
            value += tempValueList[length - 1];

            return value;
        }

        //加和
        private int SumSymbolValue(string symbol)
        {
            int value = 0;
            for (int i = 0; i < symbol.Length; i++)
            {
                value += symbol[i];
            }

            return value;
        }

        //获取字符的值
        private int GetSymbolValue(string symbol)
        {
            int value = 0;
            romanNumTable.TryGetValue(symbol, out value);

            return value;
        }
    }
}
